import {
  computed,
  defineComponent,
  inject,
  onMounted,
  onUnmounted,
  watch,
} from 'vue';
import {
  handleDragover,
  handleDrop,
  handleDragleave,
} from '@/views/editor/hooks/use-component-drag';
import {
  handleClickComponent,
  handleMousedown,
} from '@/views/editor/hooks/use-editor';
import './simulator.less';
//模拟器视图区域
export default defineComponent({
  props: {
    modelValue: Object,
  },
  setup(props, ctx) {
    const { componentMap } = inject('editorConfig');
    //获取数据
    const data = computed(() => props.modelValue);
    //更新data数据
    watch(
      () => data,
      (newVal) => {
        ctx.emit('update:modelValue', newVal);
      },
      { deep: true }
    );
    return () => (
      <div id="simulator-canvas-container">
        <div
          id="simulator"
          className="simulator"
          ondragover={handleDragover}
          ondragleave={handleDragleave}
          ondrop={(e) => handleDrop(e, data)}
          style={{
            height: data.value.container.height + 'px',
            width: data.value.container.width + 'px',
          }}>
          {data.value.components.map((component) => {
            const { id, name, config } = component;
            const style = {
              position: 'absolute',
              left: config.style.left + 'px',
              top: config.style.top + 'px',
            };
            return (
              <div
                style={style}
                id={id}
                onClick={(e) => handleClickComponent(e, component)}
                onMousedown={(e) => handleMousedown(e, component)}>
                {componentMap[name].render(config)}
              </div>
            );
          })}
        </div>
      </div>
    );
  },
});
